let ethers = require('ethers')


//随机生成密钥

let createPrivateKey = ()=>{
    let bytesValue = ethers.utils.randomBytes(32)
    let number = ethers.utils.bigNumberify(bytesValue)
    return number.toHexString()

}


//根据密钥生成钱包
let createWallet =(privateKey)=>{

    let wallet = new ethers.Wallet(privateKey)
    return wallet

}

//检验密钥是否有效
let isValid = (privateKey)=>{
    if (privateKey === ''||privateKey.match(/^[ ]+$/)){
        alert("密钥不能为空!")
        return false
    }
    if (privateKey.length !==66 && privateKey.length !== 64) {
        alert("密钥长度为66位或64位16进制数字！")
        return false
    }

    if (!privateKey.match(/^(0x)?([0-9A-Fa-f]{64})$/)) {

        alert("私钥为16进制表示,限定字符[0-9A-Fa-f]！")
        return false
    }
    return true

}

let checkAddress = (address)=>{
    try{
        address = ethers.utils.getAddress(address)
        return address
    }catch (e) {
        return ""
    }


}


//随机生成助记词

let createMnemonic=()=>{

    let value = ethers.utils.randomBytes(16)

    let words = ethers.utils.HDNode.entropyToMnemonic(value)


    return words

}
let MMICPATH_PREFIX = "m/44'/60'/0'/0/"
// 通过助记词创建钱包
let newWalletFromMmic =(mmic, path) =>{
    try{
        let wallets = []
        for (let i = 0; i < 10; i++) {
            path = MMICPATH_PREFIX + i
            let wallet = ethers.Wallet.fromMnemonic(mmic, path)
            wallets.push(wallet)
            console.log(i, wallets[i].address)
        }
        return wallets
        // return wallets[0] //我们这里先只处理一个地址
    }catch(error) {
        return ""
    }
 }

 //根据json和密码生成钱包
let newWalletFromJson = (data, pwd, callback) => {
    return new Promise(async (resolve, reject) => {
        try {
            let w = await ethers.Wallet.fromEncryptedJson(data, pwd, callback)
            resolve(w)
        } catch (error) {
            reject(error)
        }
    })
}

//通过钱包生成keyStore
let exportKeyStoreFromWallet = async (wallet,pwd,callback)=>{
    return new Promise(async (resolve,reject)=>{
        try{
            let keyStore = await  wallet.encrypt(pwd,callback)

                // console.log(parseInt(p * 100)+"%")
            resolve(keyStore)
        }catch (e) {
            reject(e)
        }
    })
}


//将函数通过对象封装 方便导出
let WalletTools = {
    createPrivateKey,
    createWallet,
    isValid,
    checkAddress,
    createMnemonic,
    newWalletFromMmic,
    newWalletFromJson,
    exportKeyStoreFromWallet,
}

module.exports = WalletTools

